#!/bin/bash

# Script to make a universal appimage
# version 0.2, 2020-06-21, hvdw

# Requirements:
# appimagetool: Download from https://github.com/AppImage/AppImageKit/releases
# jre V11: download from https://adoptopenjdk.net/releases.html. Untar it and rename resulting folder to jre (to keepit simple over the versions)
# Specify where we have installed our (unpacked) jre
JRE="/mnt/chromeos/removable/128GB/software/java/JREs/linux-jdk-11.0.12+7-jre"
IET="/mnt/chromeos/removable/128GB/software/perl/Image-ExifTool-12.58"


if [ "$1" = "" ]
then
        printf "\n\nYou have to provide the version\n\n"
        exit
fi

VER="$1"

#
printf "Remove, create and step into our AppDir\n\n"
#
AppDir="jExifToolGUI-x86_64"
rm -rf ${AppDir}
mkdir -p ${AppDir}
cd ${AppDir}

#
printf "copy the complete jar into this AppDir folder\n\n"
#
cp ../../../build/libs/jExifToolGUI-all.jar jExifToolGUI.jar

#
printf "Create folders and copy program icon and desktop file\n\n"
#
mkdir -p usr/bin
mkdir -p usr/share/jexiftoolgui
mkdir -p usr/share/applications
mkdir -p usr/share/metainfo

cp ../which usr/bin/which
chmod +x usr/bin/which
cp ../jexiftoolgui-48x48.png usr/share/jexiftoolgui
cp ../jexiftoolgui-48x48.png .
mv jExifToolGUI.jar usr/share/jexiftoolgui
cp ../jexiftoolgui.desktop usr/share/applications
cp ../jexiftoolgui.desktop .
cp ../jexiftoolgui.appdata.xml usr/share/metainfo


# As an Appimage need to be a completely portable entity, we will also include exiftool
# This requires you to download the latest exiftool from https://exiftool.org and untar it
# We simply use the "uninstalled" version. Below line specifies the version and optional path
#mkdir -p usr/local/bin
# copy everything, then clean up things not needed
cp -a ${IET}/* usr/bin
rm -rf usr/bin/t usr/bin/html usr/bin/Changes usr/bin/Makefile.PL


#
printf "Now copy the unpacked jre folder into our folder structure\n\n"
mkdir jre
cp -a --preserve=links $JRE/* ./jre

#
printf "Create the AppRun script\n\n"
#
#cd usr/bin
cat > ./AppRun <<\EOF
#!/bin/sh
HERE=$(dirname $(readlink -f "${0}"))
export LD_LIBRARY_PATH="$APPDIR/usr/bin/lib:${HERE}/usr/local/lib:${HERE}/usr/lib:$LD_LIBRARY_PATH"
export JAVA_HOME="${HERE}"/jre
export PATH="$APPDIR/usr/bin:${HERE}/usr/local/bin:${HERE}/usr/bin:$PATH"
"${HERE}"/jre/bin/java -jar "${HERE}"/usr/share/jexiftoolgui/jExifToolGUI.jar ${1+"$@"} &
EOF

chmod a+x ./AppRun

#
# We're done in the AppDir
cd ..
#rm ${AppDir}/${latest_exif}

#
# Create the AppImage
#
wget -c https://github.com/AppImage/AppImageKit/releases/download/12/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage
ARCH=x86_64 ./appimagetool-x86_64.AppImage -n ${AppDir}

#
# Rename the created app image
#
mv jExifToolGUI-x86_64.AppImage jExifToolGUI-${VER}-x86_64.AppImage
